﻿using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Helpers;
using System.Web.Mvc;
using System.Web.WebPages;

namespace Clarke.UI.Helpers
{
	public static class WebGridHelpers
	{
		public static IHtmlString GetHtmlWithSelectAllCheckBox(this WebGrid webGrid, string tableStyle = null, string headerStyle = null, string footerStyle = null,
			string rowStyle = null, string alternatingRowStyle = null, string selectedRowStyle = null, string caption = null, bool displayHeader = true, 
			bool fillEmptyRows = false, string emptyRowCellValue = null, IEnumerable<WebGridColumn> columns = null, IEnumerable<string> exclusions = null, 
			WebGridPagerModes mode = WebGridPagerModes.All, string firstText = null, string previousText = null, string nextText = null, string lastText = null, 
			int numericLinksCount = 5, object htmlAttributes = null, string checkBoxValue = "Id")
		{
			var newColumn = webGrid.Column(header: "{}",
										   format: item => new HelperResult(writer => writer.Write(string.Format("<input class='singleCheckBox' name='selectedRows' value='{0}' type='checkbox' />",
																								                 item.Value.GetType().GetProperty(checkBoxValue).GetValue(item.Value, null)))
			));

			var newColumns = columns.ToList();
			newColumns.Insert(0, newColumn);

			const string script = @"
			<script>                
                if (typeof jQuery == 'undefined')
                {
                    document.write(
                        unescape(
                        ""%3Cscript src='http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js'%3E%3C/script%3E""
                        )
                     );
                }

                $(function () {
					$('.table tr td').dblclick(function() {
						window.location = $(this).closest('tr').find('.editAction').attr('href');
					});

                    $('#allCheckBox').click(function () {
                        var isChecked = $(this).prop('checked');               
                        $('.singleCheckBox').prop('checked', isChecked ? true : false);
						if (isChecked) {
							$('.singleCheckBox').closest('div.checker').find('span').addClass('checked');
						} else {
							$('.singleCheckBox').closest('div.checker').find('span').removeClass('checked');
						}
                        $('.singleCheckBox').closest('tr').addClass(isChecked ? 'selected-row': 'not-selected-row');
                        $('.singleCheckBox').closest('tr').removeClass(isChecked ? 'not-selected-row': 'selected-row');
                    });

                    $('.singleCheckBox').click(function () {
                        var isChecked = $(this).prop('checked');
                        $(this).closest('tr').addClass(isChecked ? 'selected-row': 'not-selected-row');
                        $(this).closest('tr').removeClass(isChecked ? 'not-selected-row': 'selected-row');
                        if(isChecked && $('.singleCheckBox').length == $('.selected-row').length) {
							$('#allCheckBox').prop('checked', true);
							$('#allCheckBox').closest('div.checker').find('span').addClass('checked');
                        } else {
                            $('#allCheckBox').prop('checked', false);
							$('#allCheckBox').closest('div.checker').find('span').removeClass('checked');
						}
                    });
                });
            </script>";

			var html = webGrid.GetHtml(tableStyle, headerStyle, footerStyle, rowStyle, alternatingRowStyle, selectedRowStyle, caption, displayHeader, fillEmptyRows,
									   emptyRowCellValue, newColumns, exclusions, mode, firstText, previousText, nextText, lastText, numericLinksCount, htmlAttributes);
			return MvcHtmlString.Create(html.ToString().Replace("{}", "<input type='checkbox' id='allCheckBox'/>") + script);
		}
	}
}